using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;

namespace Globals.States
{
    public class GameState : MonoBehaviour
    {
        public static GameState Instance { get; private set; }

        [CanBeNull]
        public IState CurrentState
        {
            get
            {
                if (_currentState is null)
                {
                    return null;
                }
                return _states[_currentState];
            }
        }

        private readonly Dictionary<Type, IState> _states = new();
        private GlobalState _globalState;

        private Type _currentState;
        private Type _previousState;


        private void Awake()
        {
            Instance = this;

            _globalState = GetComponent<GlobalState>();
            
            WaitingForStartState waitingForStartState = GetComponent<WaitingForStartState>();
            _states.Add(typeof(WaitingForStartState), waitingForStartState);
            _states.Add(typeof(TutorialState), GetComponent<TutorialState>());
            _states.Add(typeof(GameStartedState), GetComponent<GameStartedState>());
            _states.Add(typeof(GameOverState), GetComponent<GameOverState>());
            _states.Add(typeof(PauseState), GetComponent<PauseState>());

            SwitchState(typeof(WaitingForStartState));
        }

        private void OnEnable()
        {
            _globalState.Enter();
        }

        private void OnDisable()
        {
            _globalState.Exit();
            CurrentState?.Exit();
        }

        private void Update()
        {
            CurrentState?.OnUpdate();
        }

        public void SwitchState(Type stateType)
        {
            CurrentState?.Exit();

            _previousState = _currentState;
            _currentState = stateType;
            
            CurrentState!.Enter();
        }

        public void SwitchToPreviousState()
        {
            // CurrentState?.Exit();
            // _currentState = _previousState;
            SwitchState(_previousState);
        }
    }
}
